from xml.sax import make_parser
from simpledcpp.core.handlers.settings_handler import SaxHandler
import sys
import os
class Settings:
	""" Class realize settings.
	Examples:
	a = Settings()
	a.get("option", "DEFAULT_OPTION_VALUE")
	a.set("option", "OPTION_VALUE")
	"""
	def __init__(self, Load = True, filename='settings.xml'):
		""" Load settings from file if Load == True. """
		if not Load:
			self.setdict = {}
			return None
		parser = make_parser()
		curHandler = SaxHandler()
		parser.setContentHandler(curHandler)
		try:
			parser.parse(open(
			os.path.join(os.getenv("HOME"),'.simpledcpp/%s'%filename)
			))
		except IOError:
			print _("Settings file not found")
		self.setdict = curHandler.setdict

        def pop(self, name):
                """ Remove option. """
                if self.setdict.has_key(name):
                        return self.setdict.pop(name)
                else:
                        return None

	def get(self, name, DefaultValue = None):
		""" Get option. """
		if self.setdict.has_key(name):
			return self.setdict[name].encode('utf-8')
		else:
			try:
				self.set(name, DefaultValue.__str__())
			except:
				self.set(name, DefaultValue)
			return DefaultValue

	def set(self, name, value):
		""" Set option. """
		if value != None:
			self.setdict[name] = value

	def stop(self):
		""" Stop settings. (Save). """
		self.save()
		print _("Settings saved.")

	def save(self, filename='settings.xml'):
		""" Save settings to file. """
		filed = open(os.path.join(os.getenv("HOME"),'.simpledcpp/%s'%filename), 'w')
		filed.write("<settings>\n")
		for name in self.setdict:
			try:
				filed.write("  <p name=\"%s\">%s</p>\n"%(name.encode('utf-8'), self.setdict[name].encode('utf-8')))
			except:
				print sys.exc_info()
		filed.write("</settings>\n")
		filed.close()
